require 'sinatra'
require 'erb'
require 'mysql2'
require 'couchrest'
require 'json'

configure do
	@ghana_couch = CouchRest.database("http://127.0.0.1:5984/ghana-national")
end

def new_mysql
	Mysql2::Client.new(:host => "localhost", :username => "root", 
		:password => "password", :database => "openmrs_archive", :reconnect => true, :connect_timeout => 1, :async => false)
end

get '/' do
	erb :patients
end

get '/patients_count.json' do
	conn = new_mysql
	results = conn.query("select count(*), year(date_created), month(date_created) from openmrs_archive.encounter where encounter_type = 18 group by year(date_created), month(date_created)")
	display = []
	results.each(:as => :array) do |row|
		display.push({:count => row[0], :year => row[1], :month => row[2]}); 
	end
	conn.close
	display.to_json
end

get '/patients_for_location.json' do
	conn = new_mysql
	year = params["year"]
	month = params["month"]
	p "*"*80
	p "year #{year} month #{month}"
	results = conn.query("select count(*), l.name from openmrs_archive.encounter e, location l where e.encounter_type = 18 and l.location_id = e.location_id and month(e.date_created) = '"+ 
		month +"' and year(e.date_created) = '"+ year +"' group by e.location_id")
	display = []
	results.each(:as => :array) do |row|
		display.push({:count => row[0], :facility_name => row[1]})
	end
	conn.close
	display.to_json
end

get '/patients_location.json' do
	conn = new_mysql
	results = conn.query("select count(*), l.name from openmrs_archive.encounter e, location l where e.encounter_type = 18 and l.location_id = e.location_id group by e.location_id")
	display = []
	results.each(:as => :array) do |row|
		display.push({:count => row[0], :facility_name => row[1]})
	end
	conn.close
	display.to_json
end

get '/forms_uploaded.json' do
	@ghana_couch.temp_view()
end
